<template>
  <input type="text" v-model="keyword" />
  <hr />
  <h3>{{ keyword }}</h3>
</template>

<script>
import { ref, customRef } from "vue";

export default {
  name: "App",
  components: {},
  setup() {
    // 自定义ref -- myRef
    function myRef(value,delay) {
      //console.log('==myRef==',value);
      let timer;
      return customRef((track, trigger) => {
        return {
          get() {
            console.log(`调get了${value}`);
            track(); // 通知vue追踪数据的变化
            return value;
          },
          set(newValue) {
            console.log(`调set了${newValue}`);
            value = newValue;
            //trigger() // 通知vue重新解析模板
            clearTimeout(timer);
            timer = setTimeout(() => {
              trigger();
            }, delay);
          },
        };
      });
    }

    //let keyword = ref('hello');// 使用内置ref
    let keyword = myRef("hello",500); // 使用自定义ref
    return { keyword };
  },
};
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
